package com.thd.framework.basic.utils;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * 获取i8n资源文件
 */
@Component
public class MessageUtils {
    private static MessageSource messageSource;
    public MessageUtils(MessageSource messageSource) {
        MessageUtils.messageSource = messageSource;
    }

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        if (StringUtils.isEmpty(code)) return null;
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }

    /**
     * 常用公共消息  参数错误
     */
    public static String getErrorForParameterInvalid(String name) {
        String errorKey = "common.error.invalid_parameter_point";
        try {
            return messageSource.getMessage(errorKey, new Object[]{name}, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return errorKey;
        }
    }
    /**
     * 常用公共消息  参数错误
     */
    public static String getErrorForNotEmpty(String name) {
        String errorKey = "common.error.can_not_empty";
        try {
            return messageSource.getMessage(errorKey, new Object[]{name}, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return errorKey;
        }
    }

    /**
     * 常用公共消息 数据未找到
     */
    public static String getErrorForDataNotFound(String name) {
        String errorKey = "common.error.data_not_found";
        try {
            return messageSource.getMessage(errorKey, new Object[]{name}, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return errorKey;
        }
    }

    /**
     * 常用公共消息 重复的数据
     */
    public static String getErrorForRepeatData(String tableName,String attribute) {
        String errorKey = "common.error.duplicate_in_db";
        try {
            return messageSource.getMessage(errorKey, new Object[]{tableName,attribute}, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return errorKey;
        }
    }

    /**
     * 常用公共消息 节点下有数据
     */
    public static String getData(String name) {
        String errorKey = "common.error.has_in_db";
        try {
            return messageSource.getMessage(errorKey, new Object[]{name}, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return errorKey;
        }
    }
}
